package crmdna.api.endpoint;

import static crmdna.common.OfyService.ofy;

import java.util.List;

import javax.annotation.Nullable;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import com.google.api.server.spi.config.Api;
import com.google.appengine.api.users.User;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.cmd.QueryKeys;

import crmdna.common.APIException;
import crmdna.common.APIResponse;
import crmdna.common.APIResponse.Status;
import crmdna.common.RequestInfo;
import crmdna.common.Utils;
import crmdna.common.config.ConfigCRMDNA;
import crmdna.member.MemberEntity;
import crmdna.participant.ParticipantEntity;
import crmdna.registration.RegistrationEntity;
import crmdna.user.User.Action;
import crmdna.user.User.ResourceType;

@Api(name = "developersOnly")
public class DevelopersOnly {
	public APIResponse purgeAllMemberData(
			@Nullable @Named("client") String client,
			@Nullable @Named("showStackTrace") Boolean showStackTrace,
			HttpServletRequest req, User user) {

		if (client == null)
			client = "isha";

		String login = null;

		try {
			login = Utils.getLoginEmail(user);

			crmdna.user.User.ensureAccess(client, login, ResourceType.MEMBER,
					0, Action.PURGEALL);
			
			//ensure dev mode is set
			boolean devMode = ConfigCRMDNA.get().toProp().devMode;
			if (! devMode) 
				throw new APIException().status(Status.ERROR_OPERATION_NOT_ALLOWED)
				.message("This operation is allowed only in dev mode");

			QueryKeys<MemberEntity> memberQueryKeys = ofy(client).load()
					.type(MemberEntity.class).keys();

			QueryKeys<ParticipantEntity> participantQueryKeys = ofy(client).load()
					.type(ParticipantEntity.class).keys();

			QueryKeys<RegistrationEntity> registrationQueryKeys = ofy(client).load()
					.type(RegistrationEntity.class).keys();
			
			List<Key<MemberEntity>> memberKeys = memberQueryKeys.list();
			List<Key<ParticipantEntity>> participantKeys = participantQueryKeys.list();
			List<Key<RegistrationEntity>> registrationKeys = registrationQueryKeys.list();
			
			
			ofy(client).delete().keys(memberKeys);
			ofy(client).delete().keys(participantKeys);
			ofy(client).delete().keys(registrationKeys);

			StringBuilder builder = new StringBuilder();
			builder.append("Deleted [" + memberQueryKeys.list().size()
					+ "] members. ");
			builder.append("Deleted [" + participantQueryKeys.list().size()
					+ "] participants. ");
			builder.append("Deleted [" + registrationQueryKeys.list().size()
					+ "] registrants. ");

			return new APIResponse().status(Status.SUCCESS).message(
					builder.toString());

		} catch (Exception ex) {
			return Utils.toAPIResponse(ex, showStackTrace,
					new RequestInfo().client(client).req(req).login(login));			
		}
	}
}
